/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.common.utils;

import static com.huawei.housekeeper.common.constant.ConfigConstant.K8S_BEARER_TOKEN;

import com.huawei.housekeeper.common.exception.Assert;

import com.google.common.base.Charsets;

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.auth.ApiKeyAuth;
import io.kubernetes.client.openapi.models.V1ConfigMap;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringBufferInputStream;

/**
 * K8s 工具类
 *
 * @author y84241604
 * @since 2022-06-22
 */
@Component
@Slf4j
@RestController
public class K8sUtil<T> {
    /**
     * k8s集群信息
     */
    @Value("${k8s.config}")
    private String K8sConfig;

    /**
     * k8s token信息
     */
    @Value("${k8s.token}")
    private String k8sToken;

    /**
     * @param configMap  configMap
     * @param namespace  命名空间名称
     * @param configName configMap名称
     */
    public void updateConfigMap(V1ConfigMap configMap, String namespace, String configName) {
        log.info("updateConfigMap:{},namespace:{},configName:{}", configMap, namespace, configName);
        CoreV1Api api = getCoreV1ApiByK8sConfig();
        try {
            api.replaceNamespacedConfigMapAsync(configName, namespace, configMap, null, null, null, null);
        } catch (ApiException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * @param namespace  命名空间名称
     * @param configName configMap名称
     * @return V1ConfigMap
     */
    public V1ConfigMap getConfigMap(String namespace, String configName) {
        log.info("getConfigMap  namespace:{},configName:{}", namespace, configName);
        CoreV1Api api = getCoreV1ApiByK8sConfig();
        V1ConfigMap configMap = null;
        try {
            configMap = api.readNamespacedConfigMap(configName, namespace, null);
        } catch (ApiException e) {
            log.error(e.getMessage(), e);
        }
        Assert.notNull(configMap, "configMap is null");
        return configMap;
    }

    /**
     * @return k8s ApiClient
     */
    public CoreV1Api getCoreV1ApiByK8sConfig() {
        CoreV1Api coreV1Api = null;
        try (InputStream is = new StringBufferInputStream(K8sConfig)) {
            Assert.notNull(is, "getResourceAsStream is null");
            try (InputStreamReader reader = new InputStreamReader(is, Charsets.UTF_8)) {
                KubeConfig kubeConfig = KubeConfig.loadKubeConfig(reader);
                ApiClient client = ClientBuilder.kubeconfig(kubeConfig).build();
                ApiKeyAuth bearerToken = (ApiKeyAuth) client.getAuthentications().get(K8S_BEARER_TOKEN);
                bearerToken.setApiKey(k8sToken);
                coreV1Api = new CoreV1Api(client);
                Assert.notNull(coreV1Api, "apiClient is null");
                log.info("coreV1Api: {}", coreV1Api);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return coreV1Api;
    }
}
